package servlet;

import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by xiebang
 * Description
 * User:小谢
 * Date:2022-03-11
 * Time:15:51
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html;charset=utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || "".equals(username) || password == null || "".equals(password)){
            String html = "<h3>输入账号或密码缺失</h3>";
            resp.getWriter().write(html);
            return;
        }

        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if (user == null){
            String html = "<h3>输入账号或密码错误</h3>";
            resp.getWriter().write(html);
            return;
        }
        if (!user.getPassword().equals(password)){
            String html = "<h3>输入账号或密码错误</h3>";
            resp.getWriter().write(html);
            return;
        }

//        创建会话，保存用户信息
        HttpSession session =  req.getSession(true);
        session.setAttribute("user",user);
        resp.sendRedirect("blog_list");

    }
}
